package com.thread.example.controller;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

/**
 * @Auther:
 * @Description:
 * @Date: 2020/1/13 10:01
 */
public class FutureTest {

    public static void main(String[] args) {
        List<String> details = new ArrayList<>();
        for (int i = 1; i < 51; i++) {
            details.add(String.valueOf(i));
        }
        List<FutureTask<String>> futureTasks = executeThread(details);
        futureTasks.forEach(stringFutureTask -> {
            try {
                String s = stringFutureTask.get();
                System.out.println("结果：  " + s);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        });

        System.out.println("结束...");
    }


    public static List<FutureTask<String>> executeThread(List<String> details) {
        List<FutureTask<String>> futures = new CopyOnWriteArrayList<>();
        ExecutorService executorService = Executors.newFixedThreadPool(4);
        for (String detail : details) {
            FutureTask<String> future = new FutureTask<>(new Callable<String>() {
                @Override
                public String call() throws Exception {
                    String a = String.valueOf(LocalDateTime.now());
                    System.out.println("开始" + a);
                    Thread.sleep(5000);
                    System.out.println("结束" + a);
                    return String.valueOf(LocalDateTime.now());
                }
            }
            );
            System.out.println("添加");
            futures.add(future);
            executorService.submit(future);
        }

        /*while (true) {
            if (futures.size() == details.size()) {
                System.out.println("while");
                break;
            }
        }*/
        System.out.println("shutdown");
        executorService.shutdown();
        return futures;
    }
}
